import axios, {
  type InternalAxiosRequestConfig,
  type AxiosResponse,
} from "axios";

// 创建 axios 实例
const service: any = axios.create({
  timeout: 50000,
  headers: { "Content-Type": "application/json;charset=utf-8" },
});

const requestBaseUrls: any = {
  VITE_API1: import.meta.env.VITE_APP_BASE_API1,
};
(function () {
  console.log("requestBaseUrls==============", requestBaseUrls);
})();

// 请求拦截器
service.interceptors.request.use(
  (config: InternalAxiosRequestConfig & { requestBaseUrl: string }) => {
    // 处理多个域名请求
    console.log(
      "requestBaseUrls[config.requestBaseUrl]",
      requestBaseUrls[config.requestBaseUrl]
    );

    config.baseURL = requestBaseUrls[config.requestBaseUrl];
    // const accessToken = localStorage.getItem('token')
    // if (accessToken) {
    // 	config.headers.Authorization = accessToken
    // }
    return config;
  },
  (error: any) => {
    return Promise.reject(error);
  }
);

// 响应拦截器
service.interceptors.response.use(
  (response: AxiosResponse) => {
    const { code, msg } = response.data;
    if (code == 200) {
      return response.data;
    }
    // 响应数据为二进制流处理(Excel导出)
    if (response.data instanceof ArrayBuffer) {
      return response;
    }

    return Promise.reject(new Error(msg || "Error"));
  },
  (error: any) => {
    console.log(error);
    // if (error.response.data) {
    // 	const { code, msg } = error.response.data
    // }
    return Promise.reject(error.message);
  }
);

// 导出 axios 实例
export default service;
